using System;
using System.Data;

namespace Pixeldyne.Core.Data
{
	/// <summary>
	/// CSV writer class for exporting DataTable objects to CSV files.
	/// </summary>
	/// <example>
	/// <code>
	/// <pre>
	/// DataTable someData = GetData();
	/// Response.Clear();
	/// Response.Buffer= true;
	/// Response.ContentType = "application/vnd.ms-excel";
	/// Response.AddHeader("Content-Disposition", "inline;filename=Clients.xls"); Response.Charset = "";
	/// this.EnableViewState = false
	/// ProduceCSV(datatable, Response.Output, true);
	/// </pre>
	/// </code>
	/// </example>
	public class CsvWriter
	{
		/// <summary>
		/// Produces the CSV.
		/// </summary>
		/// <param name="table">The table.</param>
		/// <param name="textStream">The output text stream.</param>
		/// <param name="writeHeadings">if set to <c>true</c> writes column headings.</param>
		public static void ProduceCSV(DataTable table, System.IO.TextWriter textStream, bool writeHeadings = true)
		{
			if (writeHeadings)
			{
				var stringBuilder = new System.Text.StringBuilder();

				foreach (DataColumn col in table.Columns)
				{
					stringBuilder.Append(GetWritableValue(col.Caption) + ",");
				}

				stringBuilder.Length -= 1; //  Remove the last ,
				textStream.WriteLine(stringBuilder.ToString());
			}

			foreach (DataRow row in table.Rows)
			{
				var stringBuilder = new System.Text.StringBuilder();

				foreach (DataColumn col in table.Columns)
				{
					stringBuilder.Append(GetWritableValue(row[col]) + ",");
				}

				stringBuilder.Length -= 1; //  Remove the last ,
				textStream.WriteLine(stringBuilder.ToString());
			}
		}

		/// <summary>
		/// Gets the writeable value.
		/// </summary>
		/// <param name="obj">The object.</param>
		/// <returns></returns>
		static string GetWritableValue(object obj)
		{
			return (obj == null || obj == DBNull.Value) ? string.Empty : obj.ToString().Replace(",", ";").Replace("\r\n", "|");
		}
	}
}